#include <iostream>
#include "UdpServer.hpp"
#include "Thread.hpp"

using namespace Thread;

void RecverMessage(int sockfd, const std::string &name)
{
    char buffer[1024];
    struct sockaddr_in tmp;
    socklen_t len = sizeof(tmp);

    while (1)
    {
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&tmp, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer << std::endl;
        }
        else
        {
            std::cerr << "recvfrom error" << std::endl;
        }
    }
}

void SenderMessage(int sockfd, std::string serverIp, uint16_t serverPort, const std::string &name)
{
    // 服务端的ip、端口
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverIp.c_str());
    server.sin_port = htons(serverPort);

    std::string cli_profix = name + " #"; // send-thread# hello
    // 发送数据到服务端
    while (1)
    {
        std::cout << cli_profix;
        std::string line;
        std::getline(std::cin, line);
        if (line.empty())
            continue; // 输入为空，忽略

        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n > 0)
        {
        }
        else
        {
            std::cerr << "sendto error" << std::endl;
        }
    }
}

// 客户端必须知道服务端的 ip 和 port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
    }
    std::string serverIp = argv[1];
    uint16_t serverPort = std::stoi(argv[2]);

    // 创建 socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "create socket error" << std::endl;
    }

    // 创建两个线程，一个负责发送消息，一个负责接收消息
    thread recver("recver-thread", std::bind(&RecverMessage, sockfd, std::placeholders::_1));
    thread sender("sender-thread", std::bind(&SenderMessage, sockfd, serverIp, serverPort, std::placeholders::_1));
    
    recver.Start();
    sender.Start();

    recver.Join();
    sender.Join();
    return 0;
}